/* eslint-disable no-unused-vars */
import React, { useState } from 'react';
import { 
  Layout, 
  Menu, 
  Card, 
  Table, 
  Button, 
  Modal, 
  Form, 
  Input, 
  Descriptions, 
  Tag,
  Checkbox,
  message 
} from 'antd';
import { 
  UserOutlined,
  BarChartOutlined,
  SettingOutlined,
  LogoutOutlined,
  ScheduleOutlined
} from '@ant-design/icons';
import './index.less';
import { Tabs } from 'antd';

import PatientDetail from './PatientDetail';
import PatientSearch from './PatientSearch';

const { Header, Sider, Content } = Layout;

// Mock数据
// 确保导入语句是这样的
import { 
  mockDoctorInfo,
  mockPatients,
  initialWorkRecords 
} from './mockData';

import AddPatientModal from './AddPatientModal';
import EditPatientModal from './EditPatientModal';  // 新增导入
// 引入 dayjs 库
import dayjs from 'dayjs';
import isSameOrBefore from 'dayjs/plugin/isSameOrBefore';
import isSameOrAfter from 'dayjs/plugin/isSameOrAfter';

// 扩展dayjs功能
dayjs.extend(isSameOrBefore);
dayjs.extend(isSameOrAfter);
const DoctorDashboard = () => {
  const [searchParams, setSearchParams] = useState({});
  const [collapsed, setCollapsed] = useState(false);
  const [settingsVisible, setSettingsVisible] = useState(false);
  const [activeTab, setActiveTab] = useState('profile');
  const [form] = Form.useForm();
  const [passwordForm] = Form.useForm();
  const [notificationSettings, setNotificationSettings] = useState({
    newPatient: true,
    followUp: true
  });
  const [workRecords, setWorkRecords] = useState(initialWorkRecords);
  const [tabs, setTabs] = useState([]);
  const [activeTabKey, setActiveTabKey] = useState('profile'); // Add this line
  const [deleteModalVisible, setDeleteModalVisible] = useState(false);
  const [recordToDelete, setRecordToDelete] = useState(null);
  const [addPatientVisible, setAddPatientVisible] = useState(false);
  const [editPatientVisible, setEditPatientVisible] = useState(false);  // 新增状态
  const [newPatientData, setNewPatientData] = useState({
    name: '',
    age: '',
    gender: '',
    phone: '',
    diagnosis: {
      main: '',
      severity: '',
      secondary: '',
      description: ''
    },
    medicalHistory: '',
    allergyHistory: '',
    examination: [],
    treatment: [],
    dischargeAdvice: ''
  });
  // 删除功能实现
  const handleDeleteClick = (record) => {
    setRecordToDelete({
      number: record.recordNumber,
      name: record.patient
    });
    setDeleteModalVisible(true);
  };

  const handleConfirmDelete = () => {
    setWorkRecords(prev => prev.filter(r => r.recordNumber !== recordToDelete));
    message.success(`已删除门诊号 ${recordToDelete} 的记录`);
    setDeleteModalVisible(false);
  };

  // 修改操作列中的删除按钮
  // Add handleViewPatient function before workColumns
  // 修改handleViewPatient函数：
  const handleViewPatient = (record) => {
    const tabKey = `patient-${record.recordNumber}`;
    
    // 从mockPatients中查找对应的患者完整信息
    const patientDetail = mockPatients.find(p => p.recordNumber === record.recordNumber);
    
    setTabs(prevTabs => {
      if (prevTabs.some(tab => tab.key === tabKey)) {
        setActiveTabKey(tabKey);
        return prevTabs;
      }
      
      return [
        ...prevTabs,
        {
          key: tabKey,
          label: `患者详情 - ${record.patient}`,
          children: <PatientDetail patient={{
            name: patientDetail.patient,
            admissionNumber: patientDetail.recordNumber,
            phone: patientDetail.phone,
            date: patientDetail.date,
            age: patientDetail.age,
            gender: patientDetail.gender,
            department: patientDetail.department,
            examination: patientDetail.examination,
            diagnosis: patientDetail.diagnosis,
            treatment: patientDetail.treatment,
            dischargeAdvice: patientDetail.dischargeAdvice
          }} />
        }
      ];
    });
    
    setActiveTabKey(tabKey);
  };

  // Then define workColumns
  const [editingRecord, setEditingRecord] = useState(null); // 新增状态用于跟踪正在编辑的记录

  const workColumns = [
    {
      title: '住院号',
      dataIndex: 'recordNumber',
      key: 'recordNumber',
      width: 120,
      fixed: 'left'
    },
    {
      title: '患者姓名',
      dataIndex: 'patient',
      key: 'patient',
      width: 100,
      render: (text) => (
        <Button 
          type="link" 
          className="patient-link"
          style={{ fontSize: 12 }}
        >
          {text}
        </Button>
      ),
    },
    {
      title: '日期',
      dataIndex: 'date',
      key: 'date',
      sorter: (a, b) => new Date(a.date) - new Date(b.date),
      width: 100,
      render: (text) => <span style={{ fontSize: 12 }}>{text}</span>
    },
    {
      title: '手机号',
      dataIndex: 'phone',
      key: 'phone',
      width: 120,
      render: (text) => <span style={{ fontSize: 12 }}>{text}</span>
    },
    {
      title: '操作类型',
      dataIndex: 'action',
      key: 'action',
      width: 120,
      render: (text) => <span style={{ fontSize: 12 }}>{text}</span>
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      width: 80,
      render: (status) => (
        <Tag color={status === 'completed' ? 'green' : 'orange'} style={{ fontSize: 12 }}>
          {status === 'completed' ? '已完成' : '进行中'}
        </Tag>
      )
    },
    {
      title: '操作',
      key: 'actions',
      width: 180,
      fixed: 'right',
      render: (_, record) => (
        <div style={{ display: 'flex', gap: 4, fontSize: 12 }}>
          <Button 
            type="link" 
            style={{ fontSize: 12 }}
            onClick={(e) => {
              e.preventDefault();
              e.stopPropagation();
              handleViewPatient(record);
            }}
          >
            详情
          </Button>
          <Button 
            type="link" 
            onClick={(e) => {
              e.stopPropagation();
              const patientDetail = mockPatients.find(p => p.recordNumber === record.recordNumber) || {};
              setNewPatientData({
                ...patientDetail,
                name: record.patient,
                phone: record.phone,
                date: patientDetail.date ? dayjs(patientDetail.date) : dayjs()
              });
              setEditingRecord(record);
              setEditPatientVisible(true);
            }}
            style={{ fontSize: 12 }}
          >
            修改
          </Button>
          <Button 
            type="link" 
            danger 
            onClick={(e) => {
              e.stopPropagation();
              handleDeleteClick(record);
            }}
            style={{ fontSize: 12 }}
          >
            删除
          </Button>
        </div>
      )
    }
  ];

  const handleSaveSettings = () => {
    passwordForm.validateFields()
      .then(values => {
        message.success('设置已保存');
        setSettingsVisible(false);
      })
      .catch(info => {
        console.log('Validate Failed:', info);
      });
  };

  const handleExport = (type) => {
    message.success(`正在准备${type.toUpperCase()}格式的导出文件`);
  };

  // Move handleLogout before it's used in JSX
  const handleLogout = () => {
    Modal.confirm({
      title: '确认退出',
      content: '您确定要退出当前账号吗？',
      onOk: () => message.success('已安全退出系统')
    });
  };
 // 在组件内部添加handleTabClose函数
 const handleTabClose = (targetKey) => {
  setTabs((prevTabs) => {
    const newTabs = prevTabs.filter(tab => tab.key !== targetKey);
    const closedTabIndex = prevTabs.findIndex(tab => tab.key === targetKey);
    
    if (targetKey === activeTabKey) {
      if (closedTabIndex > 0) {
        setActiveTabKey(prevTabs[closedTabIndex - 1].key);
      } else if (newTabs.length > 0) {
        setActiveTabKey(newTabs[0].key);
      } else {
        setActiveTabKey('profile');
      }
    }
    return newTabs;
  });
};
// Add filtering function for search
const filteredRecords = workRecords.filter(record => {
  if (searchParams.recordNumber && !record.recordNumber.toString().includes(searchParams.recordNumber)) {
    return false;
  }
  if (searchParams.patientName && !record.patient.includes(searchParams.patientName)) {
    return false;
  }
  if (searchParams.phone && !record.phone.includes(searchParams.phone)) {
    return false;
  }
  if (searchParams.dateRange?.length === 2) {
    const recordDate = dayjs(record.date);
    const startDate = dayjs(searchParams.dateRange[0]);
    const endDate = dayjs(searchParams.dateRange[1]);
    if (!recordDate.isBetween(startDate, endDate, null, '[]')) {
      return false;
    }
  }
  return true;
});
  return (
    <Layout className="doctor-dashboard">
      <Sider
        collapsible
        collapsed={collapsed}
        onCollapse={setCollapsed}
        width={200}
        theme="dark"
      >
        <div className="logo">COPD管理系统</div>
        <Menu 
          theme="dark" 
          mode="inline"
          defaultSelectedKeys={['profile']}
          onSelect={({ key }) => setActiveTab(key)}
        >
          <Menu.Item key="profile" icon={<UserOutlined />}>
            我的工作台
          </Menu.Item>
          <Menu.Item key="analysis" icon={<BarChartOutlined />}>
            数据分析
          </Menu.Item>
          <Menu.Item key="patientInfo" icon={<UserOutlined />}>
            患者信息
          </Menu.Item>
        </Menu>
      </Sider>
      <Modal
      title="确认删除患者记录"
      visible={deleteModalVisible}
      onOk={handleConfirmDelete}
      onCancel={() => setDeleteModalVisible(false)}
      okText="确认删除"
      cancelText="取消"
      okButtonProps={{ danger: true }}
    >
      确定要删除患者 {recordToDelete?.name} (住院号: {recordToDelete?.number}) 的记录吗？此操作不可恢复。
    </Modal>
      <Layout>
        <Header className="header" style={{ height: 40 }}>
          <div className="header-title">
            <ScheduleOutlined style={{ fontSize: '20px', flexShrink: 0 }} />
            <span style={{ whiteSpace: 'nowrap' }}>COPD管理系统</span>
          </div>
          <div className="user-actions">
            <Button 
              icon={<SettingOutlined />}
              onClick={() => setSettingsVisible(true)}
            >
              系统设置
            </Button>
            <Button
              danger
              icon={<LogoutOutlined />}
              onClick={handleLogout}
            >
              安全退出
            </Button>
          </div>
        </Header>

        <Content className="content-container">
          <Tabs
            type="editable-card"
            activeKey={activeTabKey}
            onChange={setActiveTabKey}
            onEdit={(targetKey, action) => {
              if (action === 'remove') {
                handleTabClose(targetKey); // 使用内部定义的handleTabClose
              }
            }}
            items={[
              {
                key: 'profile',
                label: '我的工作台',
                children: (
                  <div className="profile-content">
                    <Card className="profile-card">
                      <Descriptions 
                        title="医生信息" 
                        column={2}
                        bordered
                        size="small"  // 添加size属性
                        labelStyle={{ width: '80px' }}  // 设置label宽度
                        contentStyle={{ padding: '8px 12px' }}  // 调整内容区域padding
                      >
                        <Descriptions.Item label="姓名">{mockDoctorInfo.name}</Descriptions.Item>
                        <Descriptions.Item label="职称">{mockDoctorInfo.title}</Descriptions.Item>
                        <Descriptions.Item label="所属科室">{mockDoctorInfo.department}</Descriptions.Item>
                        <Descriptions.Item label="从业年限">{mockDoctorInfo.workYears}</Descriptions.Item>
                        <Descriptions.Item label="资质认证" span={2}>
                          {mockDoctorInfo.certification}
                        </Descriptions.Item>
                      </Descriptions>
                    </Card>
                    <Card 
                      className="work-records"
                      title="近期工作记录"
                      extra={<span className="record-period">最近15条记录</span>}
                    >
                      <div style={{ marginBottom: 16 }}>
                        <PatientSearch onSearch={setSearchParams} />
                      </div>
                      <div style={{ marginBottom: 16, textAlign: 'right' }}>
                        <Button 
                          type="primary" 
                          onClick={() => {
                            // 重置所有字段为空值
                            setNewPatientData({
                              name: '',
                              age: '',
                              gender: '',
                              phone: '',
                              diagnosis: {
                                main: '',
                                severity: '',
                                secondary: '',
                                description: ''
                              },
                              medicalHistory: '',
                              allergyHistory: '',
                              examination: [],
                              treatment: [],
                              dischargeAdvice: ''
                            });
                            setEditingRecord(null); // 确保设置为新增模式
                            setAddPatientVisible(true);
                          }}
                        >
                          新增患者
                        </Button>
                      </div>
                      <AddPatientModal
                        visible={addPatientVisible}
                        onCancel={() => {
                          setAddPatientVisible(false);
                          setEditingRecord(null);
                        }}
                        onOk={() => {
                          // 确保日期是有效的dayjs对象
                          const dateObj = newPatientData.date 
                            ? dayjs.isDayjs(newPatientData.date) 
                              ? newPatientData.date 
                              : dayjs(newPatientData.date)
                            : dayjs();
                          
                          if (!dateObj || !dateObj.isValid()) {
                            message.error('日期格式无效');
                            return;
                          }

                          form.validateFields()
                            .then(() => {
                              const formattedData = {
                                ...newPatientData,
                                date: dateObj.format('YYYY-MM-DD')
                              };
                              
                              if (editingRecord) {
                                setWorkRecords(prev => prev.map(r => 
                                  r.recordNumber === editingRecord.recordNumber ? {
                                    ...r,
                                    patient: formattedData.name,
                                    phone: formattedData.phone,
                                    date: formattedData.date
                                  } : r
                                ));
                                message.success(`已修改患者 ${formattedData.name} 的信息`);
                              } else {
                                const newRecordNumber = Math.max(...workRecords.map(r => r.recordNumber)) + 1;
                                setWorkRecords(prev => [{
                                  recordNumber: newRecordNumber,
                                  patient: formattedData.name,
                                  date: formattedData.date,
                                  phone: formattedData.phone,
                                  action: '新增',
                                  status: 'completed'
                                }, ...prev]);
                                message.success(`已新增患者 ${formattedData.name}`);
                              }
                              setAddPatientVisible(false);
                              setEditingRecord(null);
                            })
                            .catch(info => {
                              console.log('Validate Failed:', info);
                            });
                        }}
                        patientData={newPatientData}
                        onFieldChange={(field, value) => {
                          if (field.includes('.')) {
                            const [parent, child] = field.split('.');
                            setNewPatientData(prev => ({
                              ...prev,
                              [parent]: {
                                ...prev[parent],
                                [child]: value
                              }
                            }));
                          } else {
                            setNewPatientData(prev => ({
                              ...prev,
                              [field]: value
                            }));
                          }
                        }}
                        form={form} // 传递form实例
                      />
                      
                      {/* 新增EditPatientModal组件 */}
                      <EditPatientModal
                        visible={editPatientVisible}
                        onCancel={() => setEditPatientVisible(false)}
                        onOk={() => {
                          form.validateFields()
                            .then(() => {
                              // Ensure date is properly formatted
                              const formattedData = {
                                ...newPatientData,
                                date: newPatientData.date ? dayjs(newPatientData.date).isValid() ? dayjs(newPatientData.date).format('YYYY-MM-DD') : dayjs().format('YYYY-MM-DD') : dayjs().format('YYYY-MM-DD')
                              };
                              
                              setWorkRecords(prev => prev.map(r => 
                                r.recordNumber === editingRecord.recordNumber ? {
                                  ...r,
                                  patient: formattedData.name,
                                  phone: formattedData.phone,
                                  date: formattedData.date
                                } : r
                              ));
                              message.success('患者信息已更新');
                              setEditPatientVisible(false);
                            })
                            .catch(info => {
                              console.log('Validate Failed:', info);
                            });
                        }}
                        patientData={newPatientData}
                        onFieldChange={(field, value) => {
                          if (field.includes('.')) {
                            const [parent, child] = field.split('.');
                            setNewPatientData(prev => ({
                              ...prev,
                              [parent]: {
                                ...prev[parent],
                                [child]: value
                              }
                            }));
                          } else {
                            setNewPatientData(prev => ({
                              ...prev,
                              [field]: value
                            }));
                          }
                        }}
                        form={form}
                      />
                      <Table
                        columns={workColumns}
                        dataSource={filteredRecords}
                        rowKey="recordNumber"
                        pagination={{ pageSize: 8 }}
                        scroll={{ x: 800 }}
                        bordered
                        onRow={(record) => ({
                          className: 'work-record-row',
                          // 移除onClick处理，禁用双击打开详情
                          // 只保留className
                        })}
                      />
                    </Card>
                  </div>
                ),
                closable: false
              },
              ...tabs
            ]}
          />
        </Content>
      </Layout>
      
    </Layout>
  );
};

// Remove the external handleTabClose function
export default DoctorDashboard;


